# 5.11 Composite Primary Keys

Starting from version 2.0, JFinal ActiveRecord supports composite primary keys with a minimalist design. For Models, you need to specify the composite primary key names during mapping. Here is a specific example:

ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
// For multi-data sources, specify the composite primary key names as the second argument
arp.addMapping("user_role", "userId, roleId", UserRole.class);

// Use the specified composite primary keys to find records
UserRole.dao.findByIds(123, 456);

// Use the specified composite primary keys to delete records
UserRole.dao.deleteByIds(123, 456);
1
2
3
4
5
6
7
8
9

As shown in the code above, for Models, you only need to specify the composite primary key names when adding Model mapping. In subsequent operations, JFinal will check the number of composite primary keys supported. An exception will be thrown if the number of composite primary keys is incorrect, ensuring data safety, especially when there are insufficient composite keys. Composite primary keys are not limited to just two; they can be any number that the database supports.

For the Db + Record model, no configuration is needed for using composite primary keys; you can use them directly:

Db.findByIds("user_role", "roleId, userId", 123, 456);
Db.deleteByIds("user_role", "roleId, userId", 123, 456);
1
2
Last Updated: 9/21/2023, 8:42:09 AM